package com.ysm.smfu.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.area.CityPicker;
import com.ysm.smfu.area.ScrollerNumberPicker;
import com.ysm.smfu.bean.Categorys;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.muiltephoto.multiphotopicker.model.ImageItem;
import com.ysm.smfu.muiltephoto.multiphotopicker.util.CustomConstants;
import com.ysm.smfu.muiltephoto.multiphotopicker.util.ImageDisplayer;
import com.ysm.smfu.muiltephoto.multiphotopicker.util.IntentConstants;
import com.ysm.smfu.muiltephoto.multiphotopicker.view.ImageBucketChooseActivity;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.FileUtils;
import com.ysm.smfu.utils.IOUtils;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PopupWindowUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.RightToTopDelView;
import com.ysm.smfu.view.XEditText;
import com.ysm.smfu.welcome.SharedConfig;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/9/28.
 */
public class ShangHuActivity extends BaseActivity {
    private static final String SH = "sh";
    private static final String SH2 = "sh2";
    /*头部*/
    @BindView(R.id.title_body)
    TextView titleBody;
    //    /*代理电话*/
//    @BindView(R.id.act_shengqing_shanghu_daili_num)
//    XEditText actShengqingShanghuDailiNum;
    /*类型*/
    @BindView(R.id.act_shengqing_shanghu_phone_type)
    TextView actShengqingShanghuPhoneType;
    /*店铺名称*/
    @BindView(R.id.act_shengqing_shanghu_dianpu)
    EditText actShengqingShanghuDianpu;
    /*店铺电话*/
    @BindView(R.id.act_shengqing_dianzhu_num)
    XEditText actShengqingDianzhuNum;
    /*折扣信息*/
    @BindView(R.id.act_shengqing_profile)
    EditText actShengqingProfile;
    /*联系/服务电话*/
    @BindView(R.id.act_shengqing_connect_num)
    EditText actShengqingConnectNum;
    /*根据地图选择位置和详细地址*/
    @BindView(R.id.act_shengqing_xiangxi_location)
    TextView actShengqingXiangxiLocation;
    @BindView(R.id.act_shengqing_xiangxi_location2)
    EditText actShengqingXiangxiLocation2;
    /*营业执照*/
    @BindView(R.id.act_shengji_zhizhao)
    ImageView actShengjiZhizhao;
    /*身份证照片*/
    @BindView(R.id.act_shengji_shenfenCard)
    ImageView actShengjiShenfenCard;
    /*不是商户时显示*/
    @BindView(R.id.shengqing_shanghu_not)
    AutoLinearLayout shengqingShanghuNot;
    /*已经是商户*/
    @BindView(R.id.shengqing_shanghu_is)
    ImageView shengqingShanghuIs;
    /*商户区域*/
    @BindView(R.id.activity_shenqing_shanghu_area)
    TextView activity_shenqing_shanghu_area;
    /*选择类型时的箭头*/
    @BindView(R.id.type_arrow)
    ImageView type_arrow;
    /*选中类型*/
    @BindView(R.id.act_shengqing_shanghu_selected_type)
    TextView act_shengqing_shanghu_selected_type;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    /*警告信息*/
//    @BindView(R.id.alert_dailiNum)
//    TextView alertDailiNum;
    @BindView(R.id.shanghu_isShow)
    Switch shanghu_isShow;
    @BindView(R.id.shangjia_img)
    ImageView shangjia_img;
    @BindView(R.id.shenqing_imgs_container)
    AutoLinearLayout shenqing_imgs_container;

//    @BindView(R.id.shade)
//    View shade;

    @BindView(R.id.shanghu)
    AutoRelativeLayout shanghu;

    private int imgWidth;
    private int imgHeight;

    private String shanghuName;
    private String type;
    private String num;
    private String profile;
    private String serveceNum;
    private String location;
    private String detailAddr;
    private LatLonPoint latLonPoint;
    private String userId;
    private String provinceCode;
    private String cityCode;
    private String countryCode;
    private SharedPreferences currShared;
    private MyReceiver myReceiver;
    private AutoLinearLayout.LayoutParams layoutParams;
    private String select_id;
    private SharedPreferences sp;
    private String name;
    private ProgressDialog loadingDialog;
    private List<Categorys.Category> bList;
    private String isBusiness;

    //    商家名称正则
    private String nameRegexp = "[\\d\\w\\u4e00-\\u9fa5]{0,20}";

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_shenqing_shanghu);
        ButterKnife.bind(this);
        shanghu_isShow.setChecked(true);
        getConfig();
//        获取商家分类
        getTypeFormLocal();
        registerBroad();
        setConfig();
        titleBody.setText("申请成为商户");
        /*商户选中类型信息，默认隐藏*/
        if (TextUtils.isEmpty(selectType))
            act_shengqing_shanghu_selected_type.setVisibility(View.GONE);
    }

    @Override
    protected void initListener() {
        super.initListener();
        actShengqingProfile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 1 && (s.toString().equals("0") || s.toString().equals("."))) {
                    s.clear();
                }
                if (s.toString().length() == 2 && !s.toString().contains(".")) {
                    s.insert(1, ".");
                } else if (s.toString().length() > 3) {
                    s.delete(3, s.length());
                }
            }
        });
    }

    ArrayList<String> types = new ArrayList<>();
    ArrayList<String> type_id = new ArrayList<>();

    /**
     * 获取保存到本地的商品分类
     */
    private void getTypeFormLocal() {
        String response = sp.getString(SpKey.CATEGORY, "");
        if (TextUtils.isEmpty(response)) {
            getTypeFromOnLine();
        } else {
            dealCategorys(response);
        }
    }

    /**
     * 处理获取到的分类信息
     *
     * @param response
     */
    private void dealCategorys(String response) {
        Categorys categorys = new Gson().fromJson(response, Categorys.class);
        //    商家分类信息
        if (categorys != null)
            bList = categorys.bList;
        if (bList != null)
            for (Categorys.Category category : bList) {
                types.add(category.name);
                type_id.add(category.id);
            }
    }

    private void setConfig() {
        setPattern(actShengqingDianzhuNum);
//        setPattern(actShengqingConnectNum);
    }

    /**
     * 设置分隔属性
     *
     * @param xEditText
     */
    private void setPattern(final XEditText xEditText) {
        xEditText.setPattern(new int[]{3, 4, 4});
        xEditText.setSeparator(" ");
        xEditText.setCustomizeMarkerEnable(true);
        xEditText.setOnMarkerClickListener(new XEditText.OnMarkerClickListener() {
            @Override
            public void onMarkerClick(float x, float y) {
                xEditText.setText("");
            }
        });
    }

    /**
     * 初始配置
     */
    private void getConfig() {
        sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        name = sp.getString(SpKey.NAME, "");
        currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        userId = currShared.getString(SpKey.USERID, "");
        isBusiness = currShared.getString(SpKey.IS_BUSINESS, "");
        dealShangHu();
    }

    /**
     * 处理商户信息
     */
    private void dealShangHu() {
        if (TextUtils.equals(isBusiness, "01")) {
            //   审核已通过
            scrollView.setVisibility(View.GONE);
//           已经是商户
            shengqingShanghuIs.setVisibility(View.VISIBLE);
            shengqingShanghuIs.setImageResource(R.drawable.isshanghu);
        } else {
            chechShangHuState();
        }
    }

    /**
     * 从服务器获取商家分类
     */
    private void getTypeFromOnLine() {
        BaseProtocal.builder(true).getType(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("商家分类信息", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    sp.edit().putString(SpKey.CATEGORY, response).commit();
                    dealCategorys(response);
                }
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    /**
     * 检测商户状态
     * /business/getState
     * 用户Id:userId
     */
    private void chechShangHuState() {
        BaseProtocal.builder(true).chechShangHuState(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("返回商户状态", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String state1 = jsonObject.optString("state");
                        if (TextUtils.equals(state1, "01")) {
//                           审核已通过
                            scrollView.setVisibility(View.GONE);
//                          已经是商户
                            shengqingShanghuIs.setVisibility(View.VISIBLE);
                            shengqingShanghuIs.setImageResource(R.drawable.isshanghu);
                        } else if (TextUtils.equals(state1, "00")) {
//                            审核中
                            scrollView.setVisibility(View.GONE);
                            shengqingShanghuIs.setVisibility(View.VISIBLE);
                            shengqingShanghuIs.setImageResource(R.drawable.watting);
                        } else if (TextUtils.equals(state1, "03")) {
//                            没有申请过
                            shengqingShanghuNot.setVisibility(View.VISIBLE);
                        } else if (TextUtils.equals(state1, "02")) {
//                            被停用
                            scrollView.setVisibility(View.GONE);
                            shengqingShanghuIs.setVisibility(View.VISIBLE);
                            shengqingShanghuIs.setImageResource(R.drawable.stop);
                        }
                        currShared.edit().putString(SpKey.IS_BUSINESS, state1).commit();
                    } catch (JSONException e) {

                    }
                }
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }


    List<File> files = new ArrayList<>();

    /**
     * 注册广播接收返回的图片
     */
    private void registerBroad() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("updatePhoto");
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, intentFilter);
        layoutParams = new AutoLinearLayout.LayoutParams(UIUtils.dip2px(65), UIUtils.dip2px(65));
        layoutParams.rightMargin = 20;
    }

    boolean isCityFirst = true;
    private boolean isTypeFirst = true;

    @OnClick({R.id.act_shengqing_shanghu_phone_type, R.id.act_shengqing_shanghu_location, R.id.type_arrow,
            R.id.shangjia_img, R.id.act_shengqing_xiangxi_location,
            R.id.act_shengji_zhizhao, R.id.act_shengji_shenfenCard, R.id.shengqi_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.type_arrow:
            case R.id.act_shengqing_shanghu_phone_type:
//                选择类型
                if (types.size() == 0) {
                    return;
                }
                UIUtils.hideKeyboard(this);
                View type = PopupWindowUtil.toogleInButton(this, SH2, shanghu, R.layout.fragment_shanghu_type, null);
                if (isTypeFirst)
                    setPopupListener(type, 1);
                break;
            case R.id.act_shengqing_shanghu_location:
//                区域选择
                View shanghu = PopupWindowUtil.toogleInButton(this, SH, this.shanghu, R.layout.fragment_area, null);
                UIUtils.hideKeyboard(ShangHuActivity.this);
                if (isCityFirst)
                    setPopupListener(shanghu, 0);
                break;
            case R.id.act_shengqing_xiangxi_location:
//                打开地图选择位置
                Intent intent_map = new Intent(ShangHuActivity.this, GDActivity.class);
                startActivityForResult(intent_map, 200);
                break;

            case R.id.shangjia_img:
//                选择商户图片
//                openAlbum(102);
                Intent intent = new Intent(ShangHuActivity.this,
                        ImageBucketChooseActivity.class);
                intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE,
                        getAvailableSize());
                startActivity(intent);
                break;
            case R.id.act_shengji_zhizhao:
//                选择图片--营业执照
                openAlbum(106);
                break;
            case R.id.act_shengji_shenfenCard:
//                选择图片--身份证
                openAlbum(107);
                break;
            case R.id.shengqi_submit:
//                提交到服务器
                checkAndSubmit();
                break;
            case R.id.back:
                finish();
                break;
        }
    }


    /**
     * 校验并且提交数据
     */
    private void checkAndSubmit() {
        if (checkType()) return;
        if (checkName()) return;
//        if (checkDlNum()) return;
        if (checkNum()) return;
        if (checkProfile()) return;
        if (checkServeceNum()) return;
        if (checkLoc()) return;
        if (checkLatLon()) return;
        if (checkAddressDetail()) return;
        if (files.size() == 0) {
            showErrorDialog("必须上传门头照片");
            return;
        }
        showLoadingDialog();
        udLoadInfo();
    }

    /**
     * 检测经纬度
     *
     * @return
     */
    private boolean checkLatLon() {
        String latInfo = actShengqingXiangxiLocation.getText().toString().trim();
        if (TextUtils.isEmpty(latInfo)) {
            showErrorDialog("请选择位置信息");
            return true;
        }
        return false;
    }

    /**
     * 正在上传对话框
     */
    private void showLoadingDialog() {
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.setMessage("正在上传");
        loadingDialog.show();
////        用户点击取消对话框时的监听
//        loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
//            @Override
//            public void onCancel(DialogInterface dialog) {
//
//            }
//        });
    }

    private void cancleDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    String isAbout;
    File zhizhaoF;
    File shenfenF;

    /**
     * 上传商家信息
     */
    private void udLoadInfo() {
        if (shanghu_isShow.isChecked()) {
            isAbout = "01";
        } else {
            isAbout = "00";
        }

        if (!zhizhaoF.exists() || zhizhaoF.length() == 0) {
            showErrorDialog("请选择营业执照");
            cancleDialog();
            return;
        }
        if (!shenfenF.exists() || shenfenF.length() == 0) {
            showErrorDialog("请选择手持身份证件");
            cancleDialog();
            return;
        }
        if (files.size() == 0) {
            showErrorDialog("请选择门头照片");
            cancleDialog();
            return;
        }
        for (File file : files) {
            PrintUtil.printRespones("照片集:" + file.getAbsolutePath() + "====" + file.length());
        }
        PrintUtil.printRespones("照片：" + zhizhaoF.getAbsolutePath() + "===" + zhizhaoF.length());
        if (TextUtils.isEmpty(detailAddr))
            detailAddr = actShengqingXiangxiLocation.getText().toString().trim();
        BaseProtocal.builder(true).udLoadInfo(
                new MyStringCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        PrintUtil.printRespones("申请商户", response);
                        cancleDialog();
                        String state = JsonUtil.getState(response);
                        if (!TextUtils.equals(state, "1")) {
                            showErrorDialog(JsonUtil.getMessage(response));
                            return;
                        }
                        showDialog();
                        resetFile();
                    }

                    @Override
                    public void onFail(Exception e) {
                        cancleDialog();
                        ToastUtils.showErrToast();
                    }
                }, userId, select_id, shanghuName, num, profile, serveceNum, provinceCode, cityCode, countryCode
                , String.valueOf(latLonPoint.getLongitude()), String.valueOf(latLonPoint.getLatitude())
                , detailAddr, isAbout, zhizhaoF, shenfenF, files, ShangHuActivity.this);
    }

    /**
     * 清空压缩后的图片
     */
    private void resetFile() {
        zhizhaoF.delete();
        shenfenF.delete();
        for (File file : files) {
            file.delete();
        }
    }

    /**
     * 申请信息成功提交后弹出对话框
     */
    public void showDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setMessage("申请信息已提交,申请结果将在3-5个工作日内回复")
                .create();
        dialog.show();
    }


    //    检测详细位置
    private boolean checkAddressDetail() {
        detailAddr = actShengqingXiangxiLocation2.getText().toString().trim();
//        if (TextUtils.isEmpty(detailAddr)) { // 不进行验证，详细地址可以为空
//            showErrorDialog("请填写详细位置信息");
//            return true;
//        }
        return false;
    }


    //    检测店铺区域
    private boolean checkLoc() {
        location = activity_shenqing_shanghu_area.getText().toString().trim();
        if (TextUtils.isEmpty(location)) {
            showErrorDialog("请选择店铺区域");
            return true;
        }
        return false;
    }

    //    检测服务电话
    private boolean checkServeceNum() {
        String serveceNums = actShengqingConnectNum.getText().toString().trim();
        serveceNum = serveceNums.replace(" ", "");
        if (TextUtils.isEmpty(serveceNum)) {
            showErrorDialog("服务电话不能为空");
            return true;
        }
        return false;
    }

    //检测折扣信息
    private boolean checkProfile() {
        profile = actShengqingProfile.getText().toString().trim();
        if (TextUtils.isEmpty(profile)) {
            showErrorDialog("请输入折扣信息");
            return true;
        }
        return false;
    }

    // 检测店主手机号
    private boolean checkNum() {
        String nums = actShengqingDianzhuNum.getText().toString().trim();
        num = nums.replace(" ", "");
        if (!num.matches(SpKey.NUMREGEX)) {
            showErrorDialog("请检查手机号是否正确");
            return true;
        }
        return false;
    }

    //检测类型
    private boolean checkType() {
        type = act_shengqing_shanghu_selected_type.getText().toString().trim();
        if (TextUtils.isEmpty(type)) {
            showErrorDialog("请选择商户类型");
            return true;
        }
        return false;
    }

//    //检测代理电话
//    private boolean checkDlNum() {
//        String dlPhones = actShengqingShanghuDailiNum.getText().toString().trim();
//        dlPhone = dlPhones.replace(" ", "");
//        if (!dlPhone.matches(SpKey.NUMREGEX)) {
//            alertDailiNum.setText("手机号格式不正确");
//            ToastUtils.showToast("请将信息填写完整");
//            return true;
//        }
//        alertDailiNum.setText("");
//        return false;
//    }

    /**
     * 检测商户名称
     *
     * @return
     */
    private boolean checkName() {
        shanghuName = actShengqingShanghuDianpu.getText().toString().trim();
        if (TextUtils.isEmpty(shanghuName)) {
            showErrorDialog("请输入商户名");
            return true;
        }
        if (!shanghuName.matches(nameRegexp)) {
            showErrorDialog("只能输入汉字数字英文且不能大于20个字符！");
            return true;
        }
        return false;
    }

    private void showErrorDialog(String msg) {
        android.support.v7.app.AlertDialog dialog = new android.support.v7.app.AlertDialog.Builder(this)
                .setMessage(msg).setNegativeButton("确定", null).create();
        dialog.show();
    }

    CityPicker fragmentCityPicker;

    private void setPopupListener(View view, int i) {
        switch (i) {
            case 0:
                isCityFirst = false;
                setCity(view);
                break;
            case 1:
                isTypeFirst = false;
                setType(view);
                break;
        }

    }

    String selectType = "";

    private void setType(View view) {
        final ScrollerNumberPicker typePicker = (ScrollerNumberPicker) view.findViewById(R.id.scrollpicker);
        typePicker.setData(types);
        typePicker.setDefault(0);
        typePicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {
            @Override
            public void endSelect(int id, String text) {
                if (TextUtils.isEmpty(text))
                    return;
                int lastDay = Integer.valueOf(typePicker.getListSize());
                if (id > lastDay) {
                    typePicker.setDefault(lastDay - 1);
                }
            }

            @Override
            public void selecting(int id, String text) {

            }
        });
        TextView confirm = (TextView) view.findViewById(R.id.confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectType = typePicker.getSelectedText();
                select_id = type_id.get(types.indexOf(selectType));
                if (TextUtils.isEmpty(selectType)) {
                    ToastUtils.showToast("类型不能为空");
                    act_shengqing_shanghu_selected_type.setVisibility(View.GONE);
                    return;
                }
                PopupWindowUtil.cancel(SH2, null);
                act_shengqing_shanghu_selected_type.setVisibility(View.VISIBLE);
                act_shengqing_shanghu_selected_type.setText(selectType);
            }
        });
    }

    private void setCity(View view) {
        fragmentCityPicker = (CityPicker) view.findViewById(R.id.fragment_cityPicker);
        TextView fragment_area_confirm = (TextView) view.findViewById(R.id.fragment_area_confirm);
        fragment_area_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(fragmentCityPicker.getProvince()) || TextUtils.isEmpty(fragmentCityPicker.getCity())
                        || TextUtils.isEmpty(fragmentCityPicker.getCouny())) {
                    ToastUtils.showToast("省市区不能为空");
                    return;
                }
                String citys = fragmentCityPicker.getCity_string();
                String[] strings = citys.split("#");
                String areas = "";
                for (String str : strings) {
                    areas = areas + str;
                }
                provinceCode = fragmentCityPicker.getProvicecode();
                cityCode = fragmentCityPicker.getCitycode();
                countryCode = fragmentCityPicker.getCountryCode();
                activity_shenqing_shanghu_area.setText(areas);
                if (TextUtils.isEmpty(countryCode)) {
                    countryCode = "0";
                }
                PrintUtil.printRespones("省：" + provinceCode + "--市：" + cityCode + "---区：" + countryCode);
                PopupWindowUtil.cancel(SH, null);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {
            case 106:
                String zhizhao = setPic(resultCode, data, actShengjiZhizhao);
                zhizhaoF = reSizePic(zhizhao, 2);
                break;
            case 107:
                String shenFenCard = setPic(resultCode, data, actShengjiShenfenCard);
                shenfenF = reSizePic(shenFenCard, 2);
                break;
            case 200:
                String title = data.getExtras().getString("title", "");
                String snippet = data.getExtras().getString("snippet", "");
//                经纬度信息，上传到后台
                latLonPoint = (LatLonPoint) data.getExtras().getParcelable("latlonpoint");
                String detail = title + snippet;
                if (!TextUtils.isEmpty(detail))
                    actShengqingXiangxiLocation.setText(detail);
                break;
        }
    }

    //        还可发送的图片数
    private int getAvailableSize() {
        int availSize = CustomConstants.MAX_IMAGE_SIZE - files.size();
        if (availSize >= 0) {
            return availSize;
        }
        return 0;
    }

    /**
     * 设置相册返回的图片
     *
     * @param resultCode
     * @param data
     * @param imageView
     */
    private String setPic(int resultCode, Intent data, ImageView imageView) {
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                String realPath = getRealPathFromURI(uri);
                setImageView(imageView, realPath);
                return realPath;
            } else {
                ToastUtils.showToast("从相册获取图片失败");
                return null;
            }
        } else if (resultCode == RESULT_CANCELED) {
            return null;
        }
        return null;
    }

    // 打开本地相册
    public void openAlbum(int resquestCode) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);
        this.startActivityForResult(intent, resquestCode);
    }

    public String getRealPathFromURI(Uri contentUri) {
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            // Do not call Cursor.close() on a cursor obtained using thismethod,
            // because the activity will do that for you at the appropriate time
            Cursor cursor = this.managedQuery(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            return contentUri.getPath();
        }
    }

    private void setImageView(ImageView imageView, String realPath) {
        Bitmap bmp = loadBigImg(imageView, realPath);
        /**
         * 获取图片角度
         */
        int degree = readPictureDegree(realPath);
        if (degree <= 0) {
            imageView.setImageBitmap(bmp);
        } else {
            // 创建操作图片是用的matrix对象
            Matrix matrix = new Matrix();
            // 旋转图片动作
            matrix.postRotate(degree);
            // 创建新图片
            Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
            imageView.setImageBitmap(resizedBitmap);
            recycleBmp(resizedBitmap);
        }
    }

    /**
     * 释放图片
     */
    private void recycleBmp(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
    }

    /**
     * 对图片压缩
     *
     * @param imageView
     */
    public Bitmap loadBigImg(ImageView imageView, String url) {

        if (imgWidth == 0) {
            imgWidth = imageView.getWidth();
            imgHeight = imageView.getHeight();
        }
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 设置为true，图片不会真正的加载到内存中，而是可以拿到图片的一些附属信息，例如宽高
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(url, opts);
        // 既然要对图片做压缩处理 ，宽高信息是一定要拿到的
        int picWidth = opts.outWidth;
        int picHeight = opts.outHeight;

        // 图片不能失真  等比例缩小
        int widthScale = picWidth / imgWidth;
        int heightScale = picHeight / imgHeight;
        // 选择大比例的这个值
        int scacle = widthScale > heightScale ? widthScale : heightScale;
        // 将最终得到的压缩倍数交给系统
        opts.inSampleSize = scacle;
        // 再往下就可以真正的去加载图片到内存中了
        // 改为false 这次要真正的加载
        opts.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(url, opts);
        // 显示图片
        return bitmap;
    }

    /**
     * 压缩上传的图片
     *
     * @param point 压缩比例
     */
    public File reSizePic(String path, int point) {

//        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 设置为true，图片不会真正的加载到内存中，而是可以拿到图片的一些附属信息，例如宽高
//        opts.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(path, opts);
        // 将最终得到的压缩倍数交给系统,768,550时商家详情页大图尺寸
//        opts.inSampleSize = calculateInSampleSize(opts, 768, 550);
        // 再往下就可以真正的去加载图片到内存中了
        // 改为false 这次要真正的加载
//        opts.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        PrintUtil.printRespones("压缩前：" + bitmap.getByteCount() + "--宽高" + bitmap.getWidth() + "===" + bitmap.getHeight());
        File file = new File(FileUtils.getDir("dmh_pic"), getPhotoFileName());
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            // 显示图片
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            PrintUtil.printRespones("压缩后：" + file.length());
        } catch (FileNotFoundException e) {
        } finally {
            IOUtils.close(fos);
            recycleBmp(bitmap);
        }
        return file;
    }

    private static int calculateInSampleSize(BitmapFactory.Options options,
                                             int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
        }

        return inSampleSize;
    }

    /**
     * 读取照片exif信息中的旋转角度<br/>
     *
     * @param path 照片路径
     * @return角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
//
        }
        return degree;
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            List<ImageItem> incomingDataList = (List<ImageItem>) intent
                    .getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
            if (incomingDataList == null) {
                return;
            }
            for (int i = 0; i < incomingDataList.size(); i++) {
                ImageItem imageItem = incomingDataList.get(i);
                PrintUtil.printRespones("原路径：" + imageItem.sourcePath);
                final File file = reSizePic(imageItem.sourcePath, 2);
                PrintUtil.printRespones("压缩后的：" + file.getAbsolutePath() + "===" + file.length());
                if (files.size() < 5) {
                    files.add(file);
                    if (files.size() == 4)
                        shangjia_img.setVisibility(View.GONE);
                    else
                        shangjia_img.setVisibility(View.VISIBLE);
                    PrintUtil.printRespones("files添加的：" + file.getAbsolutePath() + "===" + file.length());
                } else {
                    ToastUtils.showToast("最多上传4张照片");
                }
//                ImageView imageView = new ImageView(UIUtils.getContext());
//                imageView.setLayoutParams(layoutParams);
//                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//                shenqing_imgs_container.addView(imageView,0);
//                ImageDisplayer.getInstance(UIUtils.getContext()).displayBmp(imageView,
//                        imageItem.thumbnailPath, imageItem.sourcePath);
                final RightToTopDelView rightToTopDelView = new RightToTopDelView(UIUtils.getContext());
                ImageDisplayer.getInstance(UIUtils.getContext()).displayBmp(rightToTopDelView.getImageView(),
                        imageItem.thumbnailPath, imageItem.sourcePath);
                rightToTopDelView.setLayoutParams(layoutParams);
                shenqing_imgs_container.addView(rightToTopDelView, 0);
                rightToTopDelView.setOnDelImg(new RightToTopDelView.DelImg() {
                    @Override
                    public void delImg() {
                        for (int i = 0; i < shenqing_imgs_container.getChildCount(); i++) {
                            if (shenqing_imgs_container.getChildAt(i) == rightToTopDelView) {
                                files.remove(i);
                                if (shangjia_img.getVisibility() == View.GONE)
                                    shangjia_img.setVisibility(View.VISIBLE);
                            }
                        }
                        shenqing_imgs_container.removeView(rightToTopDelView);
                    }
                });
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmssSS");
        return dateFormat.format(date) + ".jpg";
    }
}
